<?php

namespace App\Admin\Actions\Agent\Order;

use App\Jobs\CurveOrderPlan;
use App\Models\AgentRechargeRecord;
use App\Models\Order;
use App\Models\Setting as SettingModel;
use App\Service\WxArticleData;
use Carbon\Carbon;
use Encore\Admin\Actions\RowAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class OrderStart extends RowAction
{
    protected $selector = '.order-open';

    public $name = '开启';


    public function handle(Order $order)
    {
        //检查订单状态：只有待投放的订单可以开启
        if ($order->state != Order::ORDER_STATE_AUDIT_WAITING) {
            return $this->response()->error('订单状态错误！（非待投放状态）')->refresh();
        }

        //检查订单底价
        $bottom_price = json_decode(SettingModel::query()->firstOrCreate(['key' => 'bottom_price'], ['value' => null])->value);

        if($order->speen_order){
            //快单
            $speed_order_rate = json_decode(SettingModel::query()->firstOrCreate(['key' => 'speed_order_rate'], ['value' => null])->value);
            $speed_order_price = $bottom_price * ($speed_order_rate / 100 + 1);

            if($order->cpm < $speed_order_price){
                return $this->response()->error('当前订单出价小于系统最低出价，请修改！')->refresh();
            }
        }else{
            if($order->cpm < $bottom_price){
                return $this->response()->error('当前订单出价小于系统最低出价，请修改！')->refresh();
            }
        }

        //获取公众号初始化数据
        $read_data = WxArticleData::get($order->url);
        if ($read_data->code == 200) {
            $order->current_read_num = $order->initialization_read_num = $read_data->read_num;
        } else {
            throw new \Exception($read_data->msg);
        }

        $order->save();



        $agentInfo = $order->adminUser->agent;

        //检查余额
        $balance = $agentInfo->balance;


        //阅读数检查
        if ($order->current_read_num > $order->expect_read_num) {
            throw new \Exception('订单：【' . $order->name . '】当前阅读数【' . $order->current_read_num . '】大于期望阅读数【' . $order->expect_read_num . '】，开启失败，请修改！');
        }

        $order_price = (($order->expect_read_num - $order->initialization_read_num) / 1000) * $order->cpm;


        if ($balance < $order_price) {
            //账户余额不足
            return $this->response()->error('账户余额不足，请联系管理员充值！')->refresh();
        }

        try {
            DB::beginTransaction();


            //记录日志
            AgentRechargeRecord::query()->create([
                'admin_user_id' => $agentInfo->admin_user_id,
                'operator' => Auth::guard()->user()->name,
                'amount' => 0 - $order_price,
                'balance' => $agentInfo->balance - $order_price,
                'remark' => '订单开始，系统自动扣费'
            ]);

            $agentInfo->decrement('balance', $order_price);//扣钱

            $order->state = Order::ORDER_STATE_ON;//修改订单状态为开启

            $order->opened_at = Carbon::now()->toDateTimeString();//修改订单状态为开启

            if($order->type == 1){
                //曲线订单
                CurveOrderPlan::dispatch($order);
            }

            $order->save();


            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->error($exception->getMessage())->refresh();

        }

        return $this->response()->success('开启成功，余额已自动扣除！')->refresh();
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default order-open"></a>
HTML;
    }
}
